package com.rhino.security.utils;


import com.rhino.security.properties.SecurityProperties;
import com.rhino.security.vo.JWTTokenVO;
import com.rhino.security.vo.JwtUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 生成令牌，验证等等一些操作
 */
@Component
public class JwtTokenUtil {

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String generateToken(Map<String, Object> claims, Date expirationDate) {
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, securityProperties.getJwt().getSecret()).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(securityProperties.getJwt().getSecret()).parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * 生成令牌
     *
     * @param userDetails 用户
     * @return 令牌
     */
    public String generateToken(JwtUser userDetails) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put(Claims.SUBJECT, userDetails.getUsername());
        claims.put("name", userDetails.getName());
        claims.put("authorities", AuthorityUtils.authorityListToSet(userDetails.getAuthorities()));
        Date date = new Date();
        //long iat = date.getTime() / 1000;
        //claims.put(Claims.ISSUED_AT, iat);
        Date expirationDate = new Date(date.getTime() + securityProperties.getJwt().getAccessTokenValidity());
        return generateToken(claims, expirationDate);
    }

    /**
     * 解析jwttoken的权限信息
     *
     * @param claims Claims
     * @return: 权限集合
     **/
    public List<GrantedAuthority> getAuthorities(Claims claims) {
        List<GrantedAuthority> authoritieList = (List<GrantedAuthority>) claims.get("authorities");
        String authoritie = StringUtils.join(authoritieList, ",");
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authoritie);
    }

    /**
     * 返回一个jwt token对象
     *
     * @param userDetails 用户信息
     * @return: JWTTokenVO
     **/
    public JWTTokenVO getJWTToken(JwtUser userDetails) {
        String token = generateToken(userDetails);
        JWTTokenVO jwtTokenVO = new JWTTokenVO();
        jwtTokenVO.setAccessToken(token);
        jwtTokenVO.setRefreshToken(refreshToken(token));
        jwtTokenVO.setTokenType("bearer");
        //handleAuthority(jwtTokenVO, userDetails);
        return jwtTokenVO;
    }

    /**
     * 处理角色与权限
     *
     * @param jwtTokenVO
     * @param userDetails
     */
    public void handleAuthority(JWTTokenVO jwtTokenVO, JwtUser userDetails) {
        String rolePrefix = "ROLE_";
        List<String> roleList = new ArrayList<>();
        List<String> authorityList = new ArrayList<>();
        String authorityValue = "";
        Collection<GrantedAuthority> authorities = userDetails.getAuthorities();
        if (authorities != null && authorities.size() > 0) {
            for (GrantedAuthority authority : authorities) {
                authorityValue = authority.getAuthority();
                if (authorityValue.contains(rolePrefix)) {
                    roleList.add(authorityValue.substring(authorityValue.lastIndexOf(rolePrefix) + rolePrefix.length()));
                } else {
                    authorityList.add(authorityValue);
                }
            }
            //jwtTokenVO.setRoleList(roleList);
            //jwtTokenVO.setAuthorityList(authorityList);
        }
    }


    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }


    /**
     * 判断令牌是否过期
     *
     * @param claims 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(Claims claims) {
        try {
//            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            Date date = new Date();
            long iat = date.getTime() / 1000;
            claims.put(Claims.ISSUED_AT, iat);
            Date expirationDate = new Date(date.getTime() + securityProperties.getJwt().getRefreshTokenValidity());
            refreshedToken = generateToken(claims, expirationDate);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 验证令牌
     *
     * @param claims 令牌
     * @return 是否有效
     */
    public Boolean validateToken(Claims claims) {
        return (!isTokenExpired(claims));
    }
}